package com.yb.xczx.cloud.gateway.filter;

import com.alibaba.fastjson2.JSONObject;
import com.yb.core.enums.HttpCode;
import com.yb.core.model.WhiteListProperties;
import com.yb.core.model.XczxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * Copyright (C), 2022-2023, 姚兵
 * Author: 32210
 * Date: 2023/5/20 12:56
 * FileName: GlobalAuthFilter
 * Description:
 */
public class GlobalAuthFilter implements GlobalFilter, Ordered {
        @Autowired
        WhiteListProperties whiteListProperties;

        AntPathMatcher antPathMatcher = new AntPathMatcher();
        @Override
        public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

            ServerHttpRequest request = exchange.getRequest();
            HttpHeaders headers = request.getHeaders();


            String requestPath = request.getURI().getPath();
            boolean matched=false;

            for (String url : whiteListProperties.getUrls()) {
                if (antPathMatcher.match(url,requestPath)) {
                    matched=true;
                    break;
                }
            }
            if (matched) {
                //如果白名单则直接放行
                return chain.filter(exchange);
            }
            //不包含请求头则直返回不让访问
            if (!headers.containsKey(HttpHeaders.AUTHORIZATION)) {
                //3.3作JSON转换
                byte[] bytes = JSONObject.toJSONString(XczxResult.error(HttpCode.Response.UNAUTHORIZED)).getBytes(StandardCharsets.UTF_8);
                ServerHttpResponse response = exchange.getResponse();
                //3.4调用bufferFactory方法,生成DataBuffer对象
                response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE);

                DataBuffer buffer = response.bufferFactory().wrap(bytes);

                return  response.writeWith(Mono.just(buffer));
            }


            //包含请求头则放行
            return chain.filter(exchange);
        }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
